package com.gitee.wsl.common.ui.ext

import androidx.annotation.FloatRange
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.util.lerp
import kotlin.math.sqrt

operator fun IntSize.minus(other: IntSize): IntSize {
    return IntSize(this.width - other.width, this.height - other.height)
}

fun IntSize.length(): Float {
    return sqrt((width * width + height * height).toDouble()).toFloat()
}

@Composable
fun IntSize.toDpSize(): DpSize = with(LocalDensity.current) {
    DpSize(width.toDp(), height.toDp())
}

@Stable
fun lerp(start: IntSize, stop: IntSize, @FloatRange(from = 0.0, to = 1.0) fraction: Float): IntSize =
    IntSize(
        lerp(start.width, stop.width, fraction),
        lerp(start.height, stop.height, fraction),
    )


fun IntSize.aspectRatio(): Float = width.toFloat() / height

fun IntSize.cropTo(
    dstSize: IntSize,
): IntSize {
    val srcSize = this
    val dstAspectRatio = dstSize.aspectRatio()
    var plausibleWidth: Int
    var plausibleHeight: Int

    if (dstAspectRatio > 1) {
        plausibleWidth = srcSize.width
        plausibleHeight = (plausibleWidth / dstAspectRatio).toInt()
        if (plausibleHeight > srcSize.height) {
            plausibleHeight = srcSize.height
            plausibleWidth = (plausibleHeight * dstAspectRatio).toInt()
        }
    } else {
        plausibleHeight = srcSize.height
        plausibleWidth = (dstAspectRatio * plausibleHeight).toInt()
        if (plausibleWidth > srcSize.width) {
            plausibleWidth = srcSize.width
            plausibleHeight = (plausibleWidth / dstAspectRatio).toInt()
        }
    }

    return IntSize(
        width = plausibleWidth,
        height = plausibleHeight
    )
}
